package validate

import (
	"context"
	"gitee.com/bobo-rs/ecomp-analyzer-services/framework/dao"
	"gitee.com/bobo-rs/ecomp-analyzer-services/framework/service"
	"gitee.com/bobo-rs/ecomp-analyzer-services/library/exception"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/util/gvalid"
)

// RuleRegisterArticle 注册文章规则
func RuleRegisterArticle() {
	gvalid.RegisterRuleByMap(map[string]gvalid.RuleFunc{
		`article-exists-id`:      RuleArticleExistsById,
		`art-category-exists-id`: RuleArtCategoryExistsById,
		`art-category-del-id`:    RuleArtCategoryDeleteById,
	})
}

// RuleArticleExistsById 通过文章ID检测文章是否存在
func RuleArticleExistsById(ctx context.Context, in gvalid.RuleFuncInput) error {
	if in.Value.Uint() == 0 {
		return nil
	}
	// 是否存在
	if b, _ := service.Article().ArticleModel().ExistsPri(ctx, in.Value.Uint()); !b {
		return exception.New(`文章数据不存在`)
	}
	return nil
}

// RuleArtCategoryExistsById 通过文章分类ID检测文章分类是否存在
func RuleArtCategoryExistsById(ctx context.Context, in gvalid.RuleFuncInput) error {
	if in.Value.Uint() == 0 {
		return nil
	}
	// 是否存在
	if b, _ := service.Article().CategoryModel().ExistsPri(ctx, in.Value.Uint()); !b {
		return exception.New(`文章分类不存在`)
	}
	return nil
}

// RuleArtCategoryDeleteById 根据文章类目ID验证文章类目删除
func RuleArtCategoryDeleteById(ctx context.Context, in gvalid.RuleFuncInput) error {
	if in.Value.Uint() == 0 {
		return nil
	}
	// 是否存在子级
	if b, _ := service.Article().CategoryModel().Exists(ctx, g.Map{
		dao.ArticleCategory.Columns().Pid: in.Value.Uint(),
	}); !b {
		return exception.New(`父级类目不允许删除`)
	}
	// 是否有文章
	if b, _ := service.Article().ArticleModel().Exists(ctx, g.Map{
		dao.Article.Columns().Cid: in.Value.Uint(),
	}); !b {
		return exception.New(`该类目下存在文章不允许删除`)
	}
	return nil
}
